//
//  BodyIngredientViewController.m
//  SHHCPhone
//
//  Created by sheng long on 14-6-30.
//  Copyright (c) 2014年 sheng long. All rights reserved.
//

#import "BodyIngredientViewController.h"
#import "WeightReferenceViewController.h"
#import "BodyIngredientCell.h"
#import "BodyIngredientInfo.h"
#import "DailyDietViewController.h"
#import "MoveGuideViewController.h"
#import "SportsGuideViewController.h"
#import "HomeSideViewController.h"
#import "HomeFloatLayerView.h"

@interface BodyIngredientViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView *mainTable;
    
    BOOL isFirst;
    
    //浮层
    HomeFloatLayerView *floatLayerView;
}
@property (nonatomic,retain) NSArray *dataArray;
@end

@implementation BodyIngredientViewController

@synthesize dataArray;
@synthesize vcArray;

- (void)viewDidLoad
{
    [super viewDidLoad];
//    
//    navigationBarView.title = @"体成分";
//    [navigationBarView setNormalLeftButton];
}

-(void)viewWillAppear:(BOOL)animated
{
    for (UIView *view in navigationBarView.subviews) {
        [view removeFromSuperview];
    }
    navigationBarView.title = @"人体成分";
    [self showNavbarStyle];
}

-(void)showView
{
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, NAVIGATIONBAR_HEIGHT, CURRENT_CONTENT_WIDTH, 66)];
    bgView.backgroundColor = GET_COLOR(@"ff8cb7");
    [self.view addSubview:bgView];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:@"体成分页-进入管理按钮"] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"体成分页-进入管理按钮-点击"] forState:UIControlStateHighlighted];
    [button sizeToFit];
    [button setTitle:@"进入体重管理" forState:UIControlStateNormal];
    [button setTitleColor:GET_COLOR(@"ffffff") forState:UIControlStateNormal];
    [button.titleLabel setFont:[UIFont boldSystemFontOfSize:16]];
    [button setCenter:bgView.center];
    [button addTarget:self action:@selector(pushManage:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    mainTable = [[UITableView alloc] initWithFrame:CGRectMake(0, bgView.frame.size.height+bgView.frame.origin.y, CURRENT_CONTENT_WIDTH, CURRENT_CONTENT_HEIGHT-(bgView.frame.size.height+bgView.frame.origin.y))];
    [mainTable setDelegate:self];
    [mainTable setDataSource:self];
    [mainTable setSeparatorColor:[UIColor clearColor]];
    [mainTable setBackgroundColor:[UIColor clearColor]];
    [mainTable setBounces:NO];
    [mainTable setTableFooterView:[self setFooterView]];
    [self.view addSubview:mainTable];
    
    //浮层
    floatLayerView = [[HomeFloatLayerView alloc] initWithFrame:self.view.bounds];
    [floatLayerView setAlpha:0];
    [floatLayerView setBaseVc:self];
    [self.view addSubview:floatLayerView];
}

-(UIView*)setFooterView
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, mainTable.frame.size.width, 143)];
    [view setBackgroundColor:[UIColor clearColor]];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectZero];
    label.textColor = GET_COLOR(@"b0b0b0");
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont systemFontOfSize:14];
    label.text = @"根据测试结果获得专业指导";
    [label sizeToFit];
    [label setCenter:CGPointMake(20+label.frame.size.width/2, 12+label.frame.size.height/2)];
    [view addSubview:label];
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(label.frame.origin.x, label.frame.origin.y+label.frame.size.height+14, view.frame.size.width-label.frame.origin.x*2, 88)];
    bgView.backgroundColor = GET_COLOR(@"fbfbfb");
    bgView.layer.borderWidth = .5;
    bgView.layer.borderColor = GET_COLOR(@"dddddd").CGColor;
    bgView.layer.cornerRadius = 2;
    [view addSubview:bgView];
    
    CGFloat height = 0.5;
    UIView *gapView = [[UIView alloc]initWithFrame:CGRectMake(bgView.frame.origin.x, bgView.frame.origin.y+bgView.frame.size.height/2-height/2, bgView.frame.size.width, height)];
    gapView.backgroundColor = GET_COLOR(@"dddddd");
    [view addSubview:gapView];
    
    NSArray *array = @[@"每日食谱推荐",@"运动指导"];
    for (int i = 0 ; i < array.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button addTarget:self action:@selector(pushManage:) forControlEvents:UIControlEventTouchUpInside];
        button.backgroundColor = [UIColor clearColor];
        [button setTag:(i+1)];
        button.frame = CGRectMake(0, bgView.frame.size.height/2*i, bgView.frame.size.width, bgView.frame.size.height/2);
        [bgView addSubview:button];
        
        UIImageView *headImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"首页-心icon"]];
        [headImage sizeToFit];
        [headImage setCenter:CGPointMake(headImage.frame.size.width/2+10, button.frame.size.height/2)];
        [button addSubview:headImage];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectZero];
        label.textColor = GET_COLOR(@"8d8d8d");
        label.font = [UIFont systemFontOfSize:14];
        label.backgroundColor = [UIColor clearColor];
        label.text = [array objectAtIndex:i];
        [label sizeToFit];
        [label setCenter:CGPointMake(headImage.frame.size.width+headImage.frame.origin.x+10+label.frame.size.width/2, button.frame.size.height/2)];
        [button addSubview:label];
        
        UIImageView *arrowImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"体成分-箭头icon"]];
        [arrowImage sizeToFit];
        [arrowImage setCenter:CGPointMake(button.frame.size.width-10-arrowImage.frame.size.width/2, button.frame.size.height/2)];
        [button addSubview:arrowImage];
    }
    
    return view;
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (!isFirst) {
        isFirst = YES;
        [self againLoading];
    }
}

//重新加载数据
-(void)againLoading
{
    [self showProgressView:nil belowSubview:navigationBarView];
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:1];
    [dic setValue:IOS_BODYCOMPOSITION forKey:IOS_METHOD_NAME];
    [dic setValue:APP_USER_MSG.id forKey:@"user_id"];
    
    ASIHTTPRequest *request =  [NetUtls httpGet:self withValue:dic tag:IOS_BODYCOMPOSITION_TAG need:NO];
    [self.netArray addObject:request];
    [request startAsynchronous];
}

-(void)pushManage:(UIButton*)button
{
    CLog(@"进入下一个页面");
    switch (button.tag) {
        case 0:
            [self.navigationController pushViewController:[[WeightReferenceViewController alloc]init] animated:YES];
            break;
        case 1:
        {
            for (UIViewController *vc in vcArray) {
                if ([vc isKindOfClass:[DailyDietViewController class]]) {
                    DailyDietViewController *view = (DailyDietViewController*)vc;
                    view.showBackBtn = YES;
                    [self.navigationController pushViewController:view animated:YES];
                    break;
                }
            }
        }
            break;
        case 2:
        {
            for (UIViewController *vc in vcArray) {
                if ([vc isKindOfClass:[SportsGuideViewController class]]) {
                    SportsGuideViewController *view = (SportsGuideViewController*)vc;
                    view.showBackBtn = YES;
                    [self.navigationController pushViewController:view animated:YES];
                    break;
                }
            }
        }
            break;
        default:
            break;
    }
}

#pragma mark - ASIHTTPRequestDelegate
-(void)requestFinished:(ASIHTTPRequest *)request
{
    CLog(@"%@",[request responseString]);
    NSDictionary *dic = [[request responseString] objectFromJSONString];
    if (dic != nil) {
        if (dic.count>0) {
            [self saveLocalData:[request responseString]];
            [self loadView:[request responseString]];
        }
        [self hideProgressView];
        [self showView];
    }else{
        [self requestFailed:request];
    }
}

-(void)requestFailed:(ASIHTTPRequest *)request
{
    //是否存在本地数据
    NSString *local = [self getLocalData];
    if (local) {
        [self loadView:local];
        [self hideProgressView];
        [self showView];
    }else{
        [self clickAgainLoadingView:0];
    }
}

-(void)loadView:(NSString*)data
{
    NSDictionary *dic = [data objectFromJSONString];
    
    NSArray *array1 = @[@"体成分-体重icon",@"体成分-体脂率icon",@"体成分-肌肉率icon",@"体成分-水分icon",@"体成分-蛋白质icon",@"首页-BMIicon.png",@"体成分-基础代谢icon"];
    NSArray *array2 = @[@"weight",@"fat_percentage",@"muscle_rate",@"total_body_water",@"protein",@"bmi",@"basal_metabolism"];
    NSArray *array3 = @[@"体重  ",@"体脂率  ",@"肌肉量  ",@"水分  ",@"蛋白质  ",@"BMI  ",@"基础代谢率  "];
    NSArray *array4 = @[APP_WEIGHT_UNIT,@"%",@"%",APP_WEIGHT_UNIT,APP_WEIGHT_UNIT,[NSString stringWithFormat:@"%@/m²",APP_WEIGHT_UNIT],@"kcal/d"];
    
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:1];
    for (int i = 0; i < array1.count; i++) {
        
        NSDictionary *d = [dic objectForKey:[array2 objectAtIndex:i]];
        
        BodyIngredientInfo *info = [[BodyIngredientInfo alloc] init];
        info.headImageName = [array1 objectAtIndex:i];
        info.title = [NSString stringWithFormat:@"%@%@%@",[array3 objectAtIndex:i],[d valueForKey:@"value"],[array4 objectAtIndex:i]];
        info.layer = [d objectForKey:@"layer"];
        switch ([[d objectForKey:@"compare"] integerValue]) {
            case -1:
            {
                info.type = BODYI_TYPE_LOW;
                info.flagText = @"偏低";
            }
                break;
            case 0:
            {
                info.type = BODYI_TYPE_BZ;
                info.flagText = @"标准";
            }
                break;
            case 1:
            {
                info.type = BODYI_TYPE_HI;
                info.flagText = @"偏高";
            }
                break;
                
            default:
                break;
        }
        if (i == 0 ) {
            info.Loc = 1;
        }else if(i == array1.count-1){
            info.Loc = 2;
        }
        [array addObject:info];
    }
    
    dataArray = array;
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = [NSString stringWithFormat:@"cell%d",indexPath.section];
    BodyIngredientCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil){

        cell = [[BodyIngredientCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier size:[tableView rectForRowAtIndexPath:indexPath].size];
        [cell setBackgroundColor:[UIColor clearColor]];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
    [cell setContent:[dataArray objectAtIndex:indexPath.row]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 52;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BodyIngredientInfo *info = [dataArray objectAtIndex:indexPath.row];
    NSDictionary *dic = info.layer;
    if (dic.count>0) {
        
        NSString *min = [NSString stringWithFormat:@"%@",[dic valueForKey:@"min"]];
        NSString *max = [NSString stringWithFormat:@"%@",[dic valueForKey:@"max"]];
        if ([min isEqualToString:max]) {
            [floatLayerView setContent:@[min] tip:[dic valueForKey:@"text"]];
        }else{
            [floatLayerView setContent:@[min,max] tip:[dic valueForKey:@"text"]];
        }
    }
}

@end
